package cn.ydxiaoshuai.modules.util;

import cn.hutool.core.codec.Base64;
import cn.ydxiaoshuai.common.api.vo.api.*;
import cn.ydxiaoshuai.common.api.vo.config.LiteConfigCopywriteResult;
import cn.ydxiaoshuai.common.api.vo.config.LiteConfigSlideResult;
import cn.ydxiaoshuai.common.api.vo.linghitai.GrowOldResponseBean;
import cn.ydxiaoshuai.common.api.vo.weixin.WeiXinConts;
import cn.ydxiaoshuai.common.constant.*;
import cn.ydxiaoshuai.common.factory.BDFactory;
import cn.ydxiaoshuai.common.sdkpro.AipImageClassifyPro;
import cn.ydxiaoshuai.common.util.ChineseHerbalMedicineContsPro;
import cn.ydxiaoshuai.common.util.RedisUtil;
import cn.ydxiaoshuai.common.util.api.DrawRectUtil;
import cn.ydxiaoshuai.common.util.api.PngColoringUtil;
import cn.ydxiaoshuai.common.util.imageprocess.ImageToChar;
import cn.ydxiaoshuai.modules.conts.LogTypeConts;
import cn.ydxiaoshuai.modules.conts.RedisBizzKey;
import cn.ydxiaoshuai.modules.entity.LiteApiLog;
import cn.ydxiaoshuai.modules.entity.LiteConfigCopywrite;
import cn.ydxiaoshuai.modules.entity.LiteConfigSlide;
import cn.ydxiaoshuai.modules.liteuser.entity.LiteUserInfo;
import cn.ydxiaoshuai.modules.liteuser.service.ILiteUserInfoService;
import cn.ydxiaoshuai.modules.weixin.po.WXAccessToken;
import cn.ydxiaoshuai.modules.weixin.po.wxlite.WXBind;
import cn.ydxiaoshuai.modules.weixin.po.wxlite.WxAuthRequestBean;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cn.ydxiaoshuai.common.util.oConvertUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;

/**
 * @author xavier
 * @className ApiBeanUtil
 * @Description 放日志|处理相关对象数据
 * @Date 2020/5/14-14:36
 **/
@Component
@Slf4j
public class ApiBeanUtil {
    @Autowired
    private RedisUtil redisUtil;

    AipImageClassifyPro imageClassifyPro = BDFactory.getAipImageClassifyPro();
    AipOcr aipOcr = BDFactory.getAipOcr();
    @Autowired
    private ILiteUserInfoService liteUserInfoService;


    /**
     * @Description 日志内容
     * @param log_id        日志ID
     * @param timeConsuming 耗时
     * @param beanStr       响应内容
     * @param remoteAddr    IP
     * @param requestParam  接口参数
     * @param uri           接口路径
     * @param errorMsg      错误信息
     * @param logType       所属模块
     * @param userId        用户ID
     * @param clientName    客户端设备
     * @return void
     * @author xavier
     * @Date 2020年3月25日14:26:57
     **/
    public void putLog(String log_id, String timeConsuming, String beanStr, String remoteAddr, String requestParam, String uri, String errorMsg, Integer logType,String userId,String clientName) {
        LiteApiLog apilog = new LiteApiLog();
        apilog.setClientName(clientName);
        apilog.setLogId(log_id);
        apilog.setTimeConsuming(timeConsuming);
        apilog.setResponseText(beanStr);
        apilog.setRequestIp(remoteAddr);
        apilog.setUserId(userId);
        if (oConvertUtils.isNotEmpty(requestParam)) {
            apilog.setRequestParam(requestParam);
        }
        apilog.setRequestUrl(uri);
        if (oConvertUtils.isNotEmpty(errorMsg)) {
            apilog.setErrorMsg(errorMsg);
        }
        apilog.setLogType(logType);
        apilog.setCreateTime(new Date());
        apilog.setCreateBy(ApiCodeConts.API_LOG_CREATE_BY);
        //日志存redis
        redisUtil.lSet(ApiCodeConts.API_LOG_LIST_KEY, apilog);
    }
    /**
     * @Description 日志内容
     * @param log_id        日志ID
     * @param timeConsuming 耗时
     * @param beanStr       日志内容
     * @param remoteAddr    IP
     * @param uri           接口路径
     * @param logType       所属模块
     * @param userId        用户ID
     * @param clientName    客户端设备
     * @return void
     * @author xavier
     * @Date 2020年3月25日14:26:57
     **/
    public void putLog(String log_id, String timeConsuming, String beanStr, String remoteAddr, String uri, Integer logType,String userId,String clientName) {
        putLog(log_id, timeConsuming, beanStr, remoteAddr, null, null, uri, logType,userId,clientName);
    }

    /**
     * @param log_id        日志ID
     * @param timeConsuming 耗时
     * @param beanStr       日志内容
     * @param remoteAddr    IP
     * @param uri           接口路径
     * @param errorMsg      错误信息
     * @param logType       所属模块
     * @param userId        用户ID
     * @param clientName    客户端设备
     * @return void
     * @Description 日志内容
     * @author xavier
     * @Date 2020年3月25日14:26:57
     **/
    public void putLog(String log_id, String timeConsuming, String beanStr, String remoteAddr, String uri, String errorMsg, Integer logType,String userId,String clientName) {
        putLog(log_id, timeConsuming, beanStr, remoteAddr, null, uri, errorMsg, logType,userId,clientName);
    }
    /**
     * @author xavier
     * @Description 注册用户|更新
     * @Date  2020/5/14
     * @param openid 根据小程序openid注册|更新用户
     * @param account_code 公众号编码
     * @return cn.ydxiaoshuai.modules.weixin.po.wxlite.WXBind
     **/
    public WXBind getIsRegister(String openid,String account_code) {
        WXBind bean = new WXBind();
        WXBind.WXData data = new WXBind.WXData();
        data.setOpenid(openid);
        data.setUserType(LiteUserConts.USER_TYPE_LITE);
        data.setAccount_code(account_code);
        //查询用户表
        LambdaQueryWrapper<LiteUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LiteUserInfo::getOpenid, openid).eq(LiteUserInfo::getAccountCode, account_code);
        LiteUserInfo liteUserInfoDB = liteUserInfoService.getOne(queryWrapper);
        if (null == liteUserInfoDB) {
            LiteUserInfo liteUserInfo = new LiteUserInfo();
            liteUserInfo.setAccountCode(account_code);
            liteUserInfo.setUserId(LiteUserConts.USER_TYPE_LITE + System.currentTimeMillis());
            liteUserInfo.setOpenid(openid);
            liteUserInfo.setCreateTime(new Date());
            liteUserInfo.setVisitDate(new Date());
            liteUserInfo.setCreateBy("system");
            boolean save = liteUserInfoService.save(liteUserInfo);
            log.info("getIsRegister数据新增状态{}",save);
            data.setUserId(liteUserInfo.getUserId());
        } else {
            boolean b = liteUserInfoService.updateById(liteUserInfoDB);
            log.info("getIsRegister数据更新状态{}",b);
            data.setUserId(liteUserInfoDB.getUserId());
        }
        bean.success("获取成功", data);
        return bean;
    }
    /**
     * @Description 小程序信息处理
     * @author xavier
     * @Date 2020/4/2 15:25
     * @param wx_type  用户类型
     * @param userType 用户入口类型
     * @param userInfo 用户信息
     * @return void
     **/
    public WXBind wxUserInfoDeal(String wx_type, String userType, WxAuthRequestBean.UserInfo userInfo,String account_code) throws Exception {
        WXBind bean = new WXBind();
        WXBind.WXData data = new WXBind.WXData();
        if (LiteUserConts.USER_TYPE_LITE.equalsIgnoreCase(userType)) {
            //查询用户表
            LambdaQueryWrapper<LiteUserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LiteUserInfo::getOpenid, userInfo.getOpenid());
            //查询用户表
            LiteUserInfo liteUserInfoDB = liteUserInfoService.getOne(queryWrapper);
            if (null == liteUserInfoDB) {
               bean = getIsRegister(userInfo.getOpenid(),account_code);
            } else {
                liteUserInfoDB.setAvatarUrl(userInfo.getAvatarUrl());
                liteUserInfoDB.setAccountCode(account_code);
                if(oConvertUtils.isEmpty(liteUserInfoDB.getFirstDate())){
                    liteUserInfoDB.setFirstDate(new Date());
                } else {
                    liteUserInfoDB.setUpdateDate(new Date());
                }
                liteUserInfoDB.setGender(userInfo.getGender());
                liteUserInfoDB.setLanguage(userInfo.getLanguage());
                liteUserInfoDB.setCountry(userInfo.getCountry());
                liteUserInfoDB.setNickName(URLEncoder.encode(userInfo.getNickName(), "UTF-8"));
                liteUserInfoDB.setProvince(userInfo.getProvince());
                liteUserInfoDB.setCity(userInfo.getCity());
                liteUserInfoDB.setUpdateTime(new Date());
                liteUserInfoDB.setUpdateBy("system");
                boolean b = liteUserInfoService.updateById(liteUserInfoDB);
                log.info("数据更新状态{}",b);
                data.setUserId(liteUserInfoDB.getUserId());
            }
        }
        bean.success("处理成功", data);
        return bean;
    }

    /**
     * @author xavier
     * @Description 处理首页轮播图数据
     * @Date  2020/3/25 13:51
     * @param list 要处理的数据
     * @return LiteConfigSlideResult
     **/
    public LiteConfigSlideResult dealIndexSlideListData(List<LiteConfigSlide> list) {
        LiteConfigSlideResult bean = new LiteConfigSlideResult();
        List<LiteConfigSlideResult.SlideListData> data = new ArrayList<>();
        list.forEach(ismStoreConfigSlide -> {
            LiteConfigSlideResult.SlideListData slideListData = new LiteConfigSlideResult.SlideListData();
            slideListData.setSlide_name(ismStoreConfigSlide.getSildeName());
            slideListData.setSlide_img_url(ismStoreConfigSlide.getImgUrl());
            slideListData.setSlide_web_url(ismStoreConfigSlide.getH5Url());
            slideListData.setSlide_lite_url(ismStoreConfigSlide.getLiteUrl());
            slideListData.setSlide_sort(ismStoreConfigSlide.getSortId());
            data.add(slideListData);
        });
        bean.success("请求成功", data);
        return bean;
    }
    /**
     * @author xavier
     * @Description 处理刷新文案数据
     * @Date  2020年5月14日15:17:04
     * @param copywriteList 要处理的数据
     * @return LiteConfigCopywriteResult
     **/
    public LiteConfigCopywriteResult dealIndexCopywriteListData(List<LiteConfigCopywrite> copywriteList) {
        LiteConfigCopywriteResult bean = new LiteConfigCopywriteResult();
        LiteConfigCopywriteResult.Data data = new LiteConfigCopywriteResult.Data();
        Collections.shuffle(copywriteList);
        data.setAboveText(copywriteList.get(0).getAboveText());
        data.setBelowText(copywriteList.get(0).getBelowText());
        bean.success("请求成功", data);
        return bean;
    }
    /**
     * @author xavier
     * @Description 处理检查图片
     * @Date  2020/9/21 16:00
     * @param request
     * @param file
     * @return cn.ydxiaoshuai.modules.weixin.po.WXAccessToken
     **/
    public WXAccessToken checkImg(HttpServletRequest request, MultipartFile file) {
        WXAccessToken imgCheckBean = null;
        if(RedisBizzKey.IS_CHECK_IMG_YES.equals(redisUtil.get(RedisBizzKey.IS_CHECK_IMG).toString())){
            //公众号编码
            String account_code = ServletRequestUtils.getStringParameter(request, "account_code", "YDXSAI");
            WeiXinConts weiXinConts = (WeiXinConts) redisUtil.get(account_code);
            //图片安全检查
            imgCheckBean = WeiXinSecurityUtil.checkImg(file, weiXinConts);
        }else{
            imgCheckBean = new WXAccessToken();
            imgCheckBean.setErrcode(0);
            imgCheckBean.setErrmsg("ok");
        }
        return imgCheckBean;
    }

    /**
     * @author xavier
     * @Description easydl中草药检测
     * @Date  2020/9/21 16:00
     * @param result 接口返回的内容
     * @return cn.ydxiaoshuai.common.api.vo.api.EasyDLGeneralBean
     **/
    public EasyDLGeneralBean dealEasyBean(EasyDLBDBean result) {
        EasyDLGeneralBean bean = new EasyDLGeneralBean();
        if(result.getResults().size()>0){
            EasyDLChinesResponseBean data = ChineseHerbalMedicineContsPro.getChineseHerbalMedicineByPinyin(result.getResults().get(0).getName());
            BigDecimal score = new BigDecimal(result.getResults().get(0).getScore()*100);
            score.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            data.setScore(new java.text.DecimalFormat("#.00").format(score));
            bean.success("success","成功",data);;
        }else{
            bean.fail("not identified","未识别出中草药",410404);
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 处理斑痘痣
     * @Date  2020/9/21 16:00
     * @param object
     * @param file
     * @return cn.ydxiaoshuai.modules.weixin.po.WXAccessToken
     **/
    public AcnespotmoleBean dealFaceAcnespotmoleBean(JSONObject object,MultipartFile file) throws Exception{
        AcnespotmoleBean bean = new AcnespotmoleBean();
        if (object.get("error_code").toString().equals("222202")) {
            bean.fail(object.get("error_msg").toString(), "图片中不包含人脸", Integer.parseInt(object.get("error_code").toString()));
        } else if (object.get("error_code").toString().equals("0")) {
            MedicalBeautyAcnespotmoleResponse medicalBeautyAcnespotmoleResponse = JSON.parseObject(object.toString(), MedicalBeautyAcnespotmoleResponse.class);
            String base64 = DrawRectUtil.getReactByAcnespotmole(file.getBytes(), medicalBeautyAcnespotmoleResponse);
            AcnespotmoleBean.Data data = new AcnespotmoleBean.Data();
            data.setAcne_count(medicalBeautyAcnespotmoleResponse.getResult().getFace_list().get(0).getAcne_list().size());
            data.setSpeckle_count(medicalBeautyAcnespotmoleResponse.getResult().getFace_list().get(0).getSpeckle_list().size());
            data.setMole_count(medicalBeautyAcnespotmoleResponse.getResult().getFace_list().get(0).getMole_list().size());
            data.setImage_base64(base64);
            bean.success("detect success", "检测成功",data);
        } else {
            bean.fail(object.get("error_msg").toString(), object.get("error_msg").toString(), Integer.parseInt(object.get("error_code").toString()));
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 处理皮肤光滑度
     * @Date  2020/9/21 16:00
     * @param object
     * @param file
     * @return cn.ydxiaoshuai.modules.weixin.po.WXAccessToken
     **/
    public SkinSmoothBean dealSkinSmoothBean(JSONObject object, MultipartFile file) throws Exception{
        SkinSmoothBean bean = new SkinSmoothBean();
        if (object.get("error_code").toString().equals("222202")) {
            bean.fail(object.get("error_msg").toString(), "图片中不包含人脸", Integer.parseInt(object.get("error_code").toString()));
        } else if (object.get("error_code").toString().equals("0")) {
            MedicalBeautySkinSmoothResponse medicalBeautySkinSmoothResponse = JSON.parseObject(object.toString(), MedicalBeautySkinSmoothResponse.class);
            String base64 = DrawRectUtil.getReactBySkinSmooth(file.getBytes(), medicalBeautySkinSmoothResponse);
            SkinSmoothBean.Data data = new SkinSmoothBean.Data();
            data.setSmooth(getSmooth(medicalBeautySkinSmoothResponse.getResult().getFace_list().get(0).getSkin().getSmooth()));
            data.setImage_base64(base64);
            bean.success("detect success", "检测成功",data);
        } else {
            bean.fail(object.get("error_msg").toString(), object.get("error_msg").toString(), Integer.parseInt(object.get("error_code").toString()));
        }
        return bean;
    }

    /**
     * @author xavier
     * @Description 处理黑眼圈眼袋检测
     * @Date  2020/9/21 16:00
     * @param object
     * @param file
     * @return cn.ydxiaoshuai.modules.weixin.po.WXAccessToken
     **/
    public SkinSmoothBean dealEyeAttrBean(JSONObject object, MultipartFile file) throws Exception{
        SkinSmoothBean bean = new SkinSmoothBean();
        if (object.get("error_code").toString().equals("222202")) {
            bean.fail(object.get("error_msg").toString(), "图片中不包含人脸", Integer.parseInt(object.get("error_code").toString()));
        } else if (object.get("error_code").toString().equals("0")) {
            MedicalBeautyEyesAttrResponseBean medicalBeautyEyesAttrResponseBean = JSON.parseObject(object.toString(), MedicalBeautyEyesAttrResponseBean.class);
            String base64 = DrawRectUtil.getReactEyesAttr(file.getBytes(), medicalBeautyEyesAttrResponseBean);
            SkinSmoothBean.Data data = new SkinSmoothBean.Data();
            data.setImage_base64(base64);
            bean.success("detect success", "黑眼圈眼袋检测成功",data);
        } else {
            bean.fail(object.get("error_msg").toString(), object.get("error_msg").toString(), Integer.parseInt(object.get("error_code").toString()));
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 处理皱纹检测
     * @Date  2020/9/21 16:00
     * @param object
     * @param file
     * @return cn.ydxiaoshuai.modules.weixin.po.WXAccessToken
     **/
    public SkinSmoothBean dealWrinkleBean(JSONObject object, MultipartFile file) throws Exception{
        SkinSmoothBean bean = new SkinSmoothBean();
        if (object.get("error_code").toString().equals("222202")) {
            bean.fail(object.get("error_msg").toString(), "图片中不包含人脸", Integer.parseInt(object.get("error_code").toString()));
        } else if (object.get("error_code").toString().equals("0")) {
            MedicalBeautyWrinkleResponseBean medicalBeautySkinColorResponse = JSON.parseObject(object.toString(), MedicalBeautyWrinkleResponseBean.class);
            String base64 = DrawRectUtil.getReactByWrinkle(file.getBytes(), medicalBeautySkinColorResponse);
            SkinSmoothBean.Data data = new SkinSmoothBean.Data();
            data.setImage_base64(base64);
            data.setWrinkle_num(medicalBeautySkinColorResponse.getResult().getFace_list().get(0).getWrinkle().getWrinkle_num());
            bean.success("detect success", "皱纹检测成功",data);
        } else {
            bean.fail(object.get("error_msg").toString(), object.get("error_msg").toString(), Integer.parseInt(object.get("error_code").toString()));
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 处理肤色
     * @Date  2020/9/21 16:00
     * @param object
     * @param file
     * @return cn.ydxiaoshuai.modules.weixin.po.WXAccessToken
     **/
    public SkinSmoothBean dealSkinColorBean(JSONObject object, MultipartFile file) throws Exception{
        SkinSmoothBean bean = new SkinSmoothBean();
        if (object.get("error_code").toString().equals("222202")) {
            bean.fail(object.get("error_msg").toString(), "图片中不包含人脸", Integer.parseInt(object.get("error_code").toString()));
        } else if (object.get("error_code").toString().equals("0")) {
            MedicalBeautySkinColorResponse medicalBeautySkinColorResponse = JSON.parseObject(object.toString(), MedicalBeautySkinColorResponse.class);
            String base64 = DrawRectUtil.getReactBySkinColor(file.getBytes(), medicalBeautySkinColorResponse);
            SkinSmoothBean.Data data = new SkinSmoothBean.Data();
            data.setColor(getColor(medicalBeautySkinColorResponse.getResult().getFace_list().get(0).getSkin().getColor()));
            data.setImage_base64(base64);
            bean.success("detect success", "肤色分析成功",data);
        } else {
            bean.fail(object.get("error_msg").toString(), object.get("error_msg").toString(), Integer.parseInt(object.get("error_code").toString()));
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 处理背景色
     * @Date  2020/9/21 16:00
     * @param object
     * @param file
     * @return cn.ydxiaoshuai.modules.weixin.po.WXAccessToken
     **/
    public AcnespotmoleBean dealIDPhotoBean(JSONObject object, MultipartFile file,String colorStr) {
        AcnespotmoleBean bean = new AcnespotmoleBean();
        BodySegBean bodySegBean = JSON.parseObject(object.toString(),BodySegBean.class);
        Color backGroundColor = getBackGroundColor(colorStr);
        if(bodySegBean.getPerson_num()>=1){
            //返回处理后的图片
            String imagebase64 = PngColoringUtil.changePNGBackgroudColorByBase64(Base64.decode(bodySegBean.getForeground()), backGroundColor);
            AcnespotmoleBean.Data data = new AcnespotmoleBean.Data();
            data.setImage_base64(imagebase64);
            bean.success("success", "成功", data);
        }else{
            bean.fail("fail", "处理失败 未检测到人脸", 20200522);
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 图片转字符图
     * @Date  2020/9/24 12:41
     * @param file 图片文件
     * @return cn.ydxiaoshuai.common.api.vo.api.ImageAsciiResponse
     **/
    public ImageAsciiResponse dealAsciiBean(MultipartFile file) throws Exception{
        ImageAsciiResponse bean = new ImageAsciiResponse();
        byte[] imageByte = file.getBytes();
        InputStream inputStream = new ByteArrayInputStream(imageByte);
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        String imageBase64 = ImageToChar.txtToImageByBase64(bufferedImage);
        if (oConvertUtils.isEmpty(imageBase64)) {
            bean.fail("image to character image failed","图片转字符图片失败了",410405);
        } else {
            bean.success("success", "图片转字符图片成功",imageBase64);
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 图像识别
     * @Date  2020/9/24 15:09
     * @param file 图片文件
     * @param apiType 接口类型
     * @param request 请求
     * @param version 接口版本
     * @return cn.ydxiaoshuai.common.api.vo.api.ImageClassifyResponseBean
     **/
    public ImageClassifyResponseBean dealICRDetectBean(MultipartFile file, String apiType, HttpServletRequest request, String version) throws Exception{
        WXAccessToken imgCheckBean = null;
        ImageClassifyResponseBean bean = new ImageClassifyResponseBean();
            if(LogTypeConts.API_VERSION.equals(version)){
                imgCheckBean = checkImg(request, file);
                if(imgCheckBean.getErrcode()==0){
                    bean = dealICRDetectAPIBean(file,apiType);
                }else{
                    bean.fail("img fail", imgCheckBean.getErrmsg(),imgCheckBean.getErrcode());
                }
            }else{
                bean = dealICRDetectAPIBean(file,apiType);
            }
        return bean;
    }
    /**
     * @author xavier
     * @Description 图像处理
     * @Date  2020/9/24 15:09
     * @param file 图片文件
     * @param apiType 接口类型
     * @param request 请求
     * @param version 接口版本
     * @return cn.ydxiaoshuai.common.api.vo.api.ImageClassifyResponseBean
     **/
    public ImageClassifyResponseBean dealICRHandleBean(MultipartFile file, String apiType, HttpServletRequest request, String version)throws Exception {
        WXAccessToken imgCheckBean = null;
        ImageClassifyResponseBean bean = new ImageClassifyResponseBean();
        if(LogTypeConts.API_VERSION.equals(version)){
            imgCheckBean = checkImg(request, file);
            if(imgCheckBean.getErrcode()==0){
                bean = dealICRHandleAPIBean(file,apiType);
            }else{
                bean.fail("img fail", imgCheckBean.getErrmsg(),imgCheckBean.getErrcode());
            }
        }else{
            bean = dealICRHandleAPIBean(file,apiType);
        }
        return bean;
    }
    /**
     * @author xavier
     * @Description 图像处理
     * @Date  2020/9/24 15:09
     * @param file 图片文件
     * @param apiType 接口类型
     * @return cn.ydxiaoshuai.common.api.vo.api.ImageClassifyResponseBean
     **/
    private ImageClassifyResponseBean dealICRHandleAPIBean(MultipartFile file, String apiType)  throws Exception{
        ImageClassifyResponseBean bean = new ImageClassifyResponseBean();
        //接口返回的内容
        JSONObject fuseObject = getFuseObject(file.getBytes(), apiType);
        ImageClassifyHandleResponse handleResponse = JSON.parseObject(fuseObject.toString(), ImageClassifyHandleResponse.class);
        if(oConvertUtils.isEmpty(handleResponse.getError_msg())){
            bean.success("success", "处理成功", handleResponse.getImage());
        } else {
            bean.fail("third api error",handleResponse.getError_msg(),handleResponse.getError_code());
        }
        return bean;
    }

    /**
     * @author xavier
     * @Description 图像识别
     * @Date  2020/9/24 15:09
     * @param file 图片文件
     * @param apiType 接口类型
     * @return cn.ydxiaoshuai.common.api.vo.api.ImageClassifyResponseBean
     **/
    private ImageClassifyResponseBean dealICRDetectAPIBean(MultipartFile file, String apiType) throws Exception{
        ImageClassifyResponseBean bean = new ImageClassifyResponseBean();
        //接口返回的内容
        JSONObject fuseObject = getFuseObject(file.getBytes(), apiType);
        if(ImageClassifyApiType.redwine.toString().equals(apiType)||ImageClassifyApiType.landmark.toString().equals(apiType)||ImageClassifyApiType.currency.toString().equals(apiType)){
            ImageClassifyOtherResponse redWineLandMark = JSON.parseObject(fuseObject.toString(), ImageClassifyOtherResponse.class);
            if(oConvertUtils.isEmpty(redWineLandMark.getError_msg())){
                boolean landMark = oConvertUtils.isEmpty(redWineLandMark.getResult().getLandmark());
                boolean redWine = oConvertUtils.isEmpty(redWineLandMark.getResult().getWineNameCn()) && 0 == redWineLandMark.getResult().getHasdetail();
                boolean currency = oConvertUtils.isEmpty(redWineLandMark.getResult().getCurrencyName()) && 0 == redWineLandMark.getResult().getHasdetail();
                if(landMark&&redWine&&currency){
                    bean.fail("result null", getNoMsg(apiType),410201);
                } else {
                    bean.success("success", "识别成功", redWineLandMark.getResult());
                }
            }else{
               bean.fail("third api error",redWineLandMark.getError_msg(),redWineLandMark.getError_code());
            }
        } else {
            ImageClassifyGeneralResponse general = JSON.parseObject(fuseObject.toString(),ImageClassifyGeneralResponse.class);
            if(oConvertUtils.isEmpty(general.getError_msg())){
                int size = general.getResult().size();
                if(0==size){
                    bean.fail("result null", getNoMsg(apiType),410201);
                }else{
                    String name = general.getResult().get(0).getName();
                    if(ImageClassifyNoneName.DISH.equals(name)||ImageClassifyNoneName.PLANT.equals(name)||ImageClassifyNoneName.ANIMAL.equals(name)||
                            ImageClassifyNoneName.INGREDIENT.equals(name)||ImageClassifyNoneName.CAR.equals(name)||
                            ImageClassifyNoneName.FLOWER.equals(name)){
                        bean.fail("result null", getNoMsg(apiType),410201);
                    } else {
                        //处理置信度
                        general.getResult().forEach(result -> {
                            if(oConvertUtils.isNotEmpty(result.getScore())){
                                double score = result.getScore();
                                result.setScore(getPercentDouble(score));
                            }
                            if(oConvertUtils.isNotEmpty(result.getProbability())){
                                String probability = result.getProbability();
                                if(probability.contains("E")||probability.contains("e")){
                                    result.setProbability("0");
                                }else{
                                    result.setProbability(getPercent(probability));
                                }
                            }
                        });
                        if(ImageClassifyApiType.car.toString().equals(apiType)){
                            String carDealBase64 = DrawRectUtil.getReact(file.getBytes(), general);
                            bean.success("success", "识别成功", general.getResult(),general.getColor_result(),general.getResult_num(),carDealBase64);
                        }else{
                            bean.success("success", "识别成功", general.getResult(),general.getColor_result(),general.getResult_num());
                        }
                    }
                }
            }else{
                bean.fail("third api error",general.getError_msg(),general.getError_code());
            }
        }
        return bean;
    }

    /**
     * @author xavier
     * @Description 处理数据
     * @Date  2020/11/2 16:54
     * @param recommendResponseBean 接口数据
     * @param bean 返回的对象
     * @return void
     **/
    public void dealClothingData(RecommendResponseBean recommendResponseBean, RecommendBean bean) {
        if (JDAIConts.CODE_10000.equals(recommendResponseBean.getCode()) && JDAIConts.STATUS_CODE_0.equals(recommendResponseBean.getResult().getStatus_code())) {
            RecommendResponseBean.ResultBean result = recommendResponseBean.getResult();
            result.getOutfits().forEach(outfitsBean -> {
                outfitsBean.setScore(getPercentDouble(outfitsBean.getScore()));
            });
            bean.success("ok", "查询成功-穿衣搭配", recommendResponseBean.getResult().getOutfits().size(), result);
        } else {
            bean.fail(recommendResponseBean.getResult().getStatus_message(), recommendResponseBean.getResult().getStatus_message(), Integer.parseInt(recommendResponseBean.getResult().getStatus_code()));
        }
    }
    /**
     * @author xavier
     * @Description 处理数据
     * @Date  2020/11/2 16:54
     * @param imgColorResponseBean 接口数据
     * @param bean 返回的对象
     * @return void
     **/
    public void dealColorData(ImgColorResponseBean imgColorResponseBean, ImgColorBean bean) {
        if(JDAIConts.CODE_10000.equals(imgColorResponseBean.getCode())&&JDAIConts.STATUS_CODE_0.equals(imgColorResponseBean.getResult().getStatus_code())){
            ImgColorResponseBean.ResultBean result = imgColorResponseBean.getResult();
            result.getColor_list().forEach(colorListBean -> {
                colorListBean.setPercentage(getPercentDouble(colorListBean.getPercentage()));
            });
            bean.success("ok", "查询成功-颜色识别", result);
        }else{
            bean.fail(imgColorResponseBean.getResult().getStatus_message(),imgColorResponseBean.getResult().getStatus_message(), Integer.parseInt(imgColorResponseBean.getResult().getStatus_code()));
        }
    }

    /**
     * @author xavier
     * @Description 皮肤光滑程度说明
     * @Date  2020/4/14 14:55
     * @param smooth 皮肤光滑度分级，1~4，越小越光滑
     * @return java.lang.String
     **/
    private String getSmooth(int smooth) {
        String smoothStr = "未知";
        if(smooth==1){
            smoothStr = "肤若凝脂,吹弹可破";
        }
        if(smooth==2){
            smoothStr = "良好";
        }
        if(smooth==3){
            smoothStr = "普普通通";
        }
        if(smooth==4){
            smoothStr = "飞沙走石";
        }
        return  smoothStr;
    }
    /**
     * @author xavier
     * @Description 肤色说明
     * @Date  2020年4月16日18:13:38
     * @param color 肤色分级，1~6，越小越浅
     * @return java.lang.String
     **/
    private String getColor(int color) {
        String colorStr = "未知";
        if(color==1){
            colorStr = "十分浅";
        }
        if(color==2){
            colorStr = "浅";
        }
        if(color==3){
            colorStr = "中等";
        }
        if(color==4){
            colorStr = "深";
        }
        if(color==5){
            colorStr = "十分深";
        }
        if(color==6){
            colorStr = "深不可测";
        }
        return  colorStr;
    }
    /**
     * @author xavier
     * @Description 背景色
     * @Date  2020年4月16日18:13:38
     * @param colorStr 修改后的颜色
     * @return java.lang.String
     **/
    private Color getBackGroundColor(String colorStr) {
        Color backgroudColor = null;
        if(colorStr.equals("red")){
            backgroudColor = Color.RED;
        }
        if(colorStr.equals("blue")){
            backgroudColor = Color.BLUE;
        }
        if(colorStr.equals("black")){
            backgroudColor = Color.BLACK;
        }
        if(colorStr.equals("white")){
            backgroudColor = Color.WHITE;
        }
        return backgroudColor;
    }

    /**
     * 根据接口类型返回提示数据
     * @param apiType
     * @return
     */
    private String getNoMsg(String apiType) {
        String msg ="";
        if(ImageClassifyApiType.dish.toString().equals(apiType)){
            msg ="未能识别出菜品 Sorry";
        }else if(ImageClassifyApiType.plant.toString().equals(apiType)){
            msg ="未能识别出植物 Sorry";
        } else if (ImageClassifyApiType.animal.toString().equals(apiType)) {
            msg ="未能识别出动物 Sorry";
        }else if (ImageClassifyApiType.ingredient.toString().equals(apiType)) {
            msg ="未能识别出果蔬食材 Sorry";
        }else if (ImageClassifyApiType.logo.toString().equals(apiType)) {
            msg ="未能识别出logo Sorry";
        }else if (ImageClassifyApiType.car.toString().equals(apiType)) {
            msg ="未能识别出汽车 Sorry";
        } else if (ImageClassifyApiType.flower.toString().equals(apiType)) {
            msg ="未能识别出花卉 Sorry";
        } else if (ImageClassifyApiType.landmark.toString().equals(apiType)) {
            msg ="未能识别出地标 Sorry";
        } else if (ImageClassifyApiType.redwine.toString().equals(apiType)) {
            msg ="未能识别出红酒 Sorry";
        } else if (ImageClassifyApiType.driverbehavior.toString().equals(apiType)) {
            msg ="未能分析出驾驶行为 Sorry";
        } else if (ImageClassifyApiType.currency.toString().equals(apiType)) {
            msg ="未能识别出货币 Sorry";
        } else {
            msg ="未能识别出内容 Sorry";
        }
        return msg;
    }
    /**
     * 根据接口类型 进行调用接口
     * @param image 识别的图片byte
     * @param apiType 接口类型
     * @return JSONObject
     */
    private JSONObject getFuseObject(byte[] image, String apiType) {
        HashMap<String, String> option = new HashMap<String, String>(16);
        option.put("top_num", "5");
        option.put("baike_num", "5");
        JSONObject jsonObject = new JSONObject();
        if(ImageClassifyApiType.dish.toString().equals(apiType)){
            jsonObject = imageClassifyPro.dishDetect(image, option);
        }
        if(ImageClassifyApiType.animal.toString().equals(apiType)){
            jsonObject = imageClassifyPro.animalDetect(image, option);
        }
        if(ImageClassifyApiType.plant.toString().equals(apiType)){
            jsonObject = imageClassifyPro.plantDetect(image, option);
        }
        if(ImageClassifyApiType.ingredient.toString().equals(apiType)){
            jsonObject = imageClassifyPro.ingredient(image, option);
        }
        if(ImageClassifyApiType.car.toString().equals(apiType)){
            jsonObject = imageClassifyPro.carDetect(image, option);
        }
        if(ImageClassifyApiType.logo.toString().equals(apiType)){
            jsonObject = imageClassifyPro.logoSearch(image, option);
        }
        if(ImageClassifyApiType.flower.toString().equals(apiType)){
            jsonObject = imageClassifyPro.flower(image, option);
        }
        if(ImageClassifyApiType.landmark.toString().equals(apiType)){
            jsonObject = imageClassifyPro.landmark(image, option);
        }
        if(ImageClassifyApiType.redwine.toString().equals(apiType)){
            jsonObject = imageClassifyPro.redwine(image, option);
        }
        if(ImageClassifyApiType.driverbehavior.toString().equals(apiType)){
            jsonObject = imageClassifyPro.driverBehavior(image, option);
        }
        if(ImageClassifyApiType.currency.toString().equals(apiType)){
            jsonObject = imageClassifyPro.currency(image, option);
        }
        if(ImageClassifyApiType.colourize.toString().equals(apiType)){
            jsonObject = imageClassifyPro.colourize(image);
        }
        return jsonObject;
    }

    /**
     * 获取银行卡类型中文说明
     * @param bank_card_type 0:不能识别; 1: 借记卡; 2: 信用卡
     * @return String
     */
    private String getBankCardType(String bank_card_type) {
        String result = "";
        if(OcrContants.BANK_CARD_TYPE_0.equals(bank_card_type)){
            result = "不能识别";
        }else if (OcrContants.BANK_CARD_TYPE_1.equals(bank_card_type)) {
            result = "借记卡";
        }else if (OcrContants.BANK_CARD_TYPE_2.equals(bank_card_type)) {
            result = "信用卡";
        }else {
            result = "未知";
        }
        return result;
    }
    /**
     * 获取身份证状态中文说明
     * @param image_status
     * @return
     */
    private String getImageStatus(String image_status) {
        String result = "";
        if(OcrContants.IMAGE_STATUS_NORMAL.equals(image_status)){
            result = "识别正常";
        }else if (OcrContants.IMAGE_STATUS_REVERSED_SIDE.equals(image_status)) {
            result = "身份证正反面颠倒";
        }else if (OcrContants.IMAGE_STATUS_NON_IDCARD.equals(image_status)) {
            result = "上传的图片中不包含身份证";
        }else if (OcrContants.IMAGE_STATUS_BLURRED.equals(image_status)) {
            result = "身份证模糊";
        }else if (OcrContants.IMAGE_STATUS_OTHER_TYPE_CARD.equals(image_status)) {
            result = "其他类型证照";
        }else if (OcrContants.IMAGE_STATUS_OVER_EXPOSURE.equals(image_status)) {
            result = "身份证关键字段反光或过曝";
        }else if (OcrContants.IMAGE_STATUS_UNKNOWN.equals(image_status)) {
            result = "未知状态";
        }else {
            result = "未知";
        }
        return result;
    }
    /**
     * 身份证类型: normal-正常身份证；copy-复印件；temporary-临时身份证；screen-翻拍；unknow-其他未知情况
     * @param riskType
     * @return
     */
    private String getRiskType(String riskType) {
        String result = "";
        if(OcrContants.RISK_TYPE_NORMAL.equals(riskType)){
            result = "正常身份证";
        }else if (OcrContants.RISK_TYPE_COPY.equals(riskType)) {
            result = "复印件";
        }else if (OcrContants.RISK_TYPE_SCREEN.equals(riskType)) {
            result = "翻拍";
        }else if (OcrContants.RISK_TYPE_UNKNOWN.equals(riskType)) {
            result = "其他未知情况";
        }else if (OcrContants.RISK_TYPE_TEMPORARY.equals(riskType)) {
            result = "临时身份证";
        }else {
            result = "未知";
        }
        return result;
    }
    /**
     *  获取文字识别结果
     * @param apiType
     * @param image
     * @param option
     * @return
     */
    private JSONObject getOcrJson(String apiType, byte[] image, HashMap<String, String> option) {
        JSONObject jsonObject = null;
        if(OcrApiType.general.toString().equals(apiType)){
            jsonObject = aipOcr.basicGeneral(image, option);
        }else if (OcrApiType.idcardb.toString().equals(apiType)) {
            option.put("detect_risk", "true");
            jsonObject = aipOcr.idcard(image, "back", option);
        }else if (OcrApiType.idcardf.toString().equals(apiType)) {
            option.put("detect_risk", "true");
            jsonObject = aipOcr.idcard(image, "front", option);
        }else if (OcrApiType.bank.toString().equals(apiType)) {
            option.put("detect_risk", "true");
            jsonObject = aipOcr.bankcard(image,option);
        }else if (OcrApiType.handwriting.toString().equals(apiType)) {
            jsonObject = aipOcr.handwriting(image, null);
        }else {
            jsonObject = null;
        }
        return jsonObject;
    }
    /**
     * 获取2位小数
     * @param num
     * @return num
     */
    private static double getPercentDouble(double num) {
        BigDecimal bigDecimal = new BigDecimal(num);
        BigDecimal percentage = new BigDecimal(100);
        BigDecimal decimal = bigDecimal.setScale(4, BigDecimal.ROUND_HALF_DOWN);
        return decimal.multiply(percentage).setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
    }

    /**
     * 获取2位小数
     * @param num
     * @return num
     */
    private static String getPercent(String num) {
        BigDecimal bigDecimal = new BigDecimal(num);
        BigDecimal percentage = new BigDecimal(100);
        BigDecimal decimal = bigDecimal.setScale(4, BigDecimal.ROUND_HALF_DOWN);
        return decimal.multiply(percentage).setScale(2,BigDecimal.ROUND_HALF_DOWN).toPlainString();
    }


}
